package com.duan.oauth.service.impl;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.duan.oauth.service.AuthService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class AuthServiceImpl implements AuthService {

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private RedisTemplate redisTemplate;
    @Value("${auth.ttl}")
    private int ttl;

    @Override
    public Map login(String username, String password, String clientId, String clientSecret) {
        if (username == null || username.equals("")) {
            throw new RuntimeException("用户名不能为空");
        }
        if (password == null || password.equals("")) {
            throw new RuntimeException("密码不能为空");
        }
        //参数
        Map paramMap = new HashMap();
        paramMap.put("grant_type","password");
        paramMap.put("username",username);
        paramMap.put("password",password);
        paramMap.put("client_id",clientId);
        paramMap.put("client_secret",clientSecret);

        String post = HttpUtil.post("http://localhost:9200/oauth/token", paramMap);
        Map map = null;
        try {
            map = JSON.parseObject(post, Map.class);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        if (map == null || map.get("access_token") == null) {
            throw new RuntimeException("申请令牌失败");
        }
        redisTemplate.opsForValue().set(map.get("jti"),map.get("access_token"),ttl, TimeUnit.MINUTES);
        return map;
    }
}

